﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Secondary_File_System.lib;

namespace Secondary_File_System.Model
{
    class User
    {
        //Configuration
        public const int usernameBytesLimit = 200;
        public const int passwordBytesLimit = 200;

        //Properties
        public int index { get; set; }
        public string username { get; set; }
        public string password { get; set; }
        public int directoryIndex { get; set; }

        public static User readFromStream(ref FileStream fs)
        {
            User user = new User();
            user.index = Utility.readIntFromStream(ref fs);
            user.username = Utility.readStringFromStream(ref fs, usernameBytesLimit);
            user.password = Utility.readStringFromStream(ref fs, passwordBytesLimit);
            user.directoryIndex = Utility.readIntFromStream(ref fs);
            return user;
        }
        public void save(ref FileStream fs)
        {
            byte[] bufferUsername = FileSystem.systemEncoding.GetBytes(this.username);
            byte[] bufferPassword = FileSystem.systemEncoding.GetBytes(this.password);
            byte[] tmpBuffer;
            if (bufferUsername.Length > usernameBytesLimit)
            {
                Console.WriteLine("【CRITICAL ERROR】用户名过长！保存失败！\n【CRITICAL ERROR】操作已回滚，按下任意键退出...");
                Console.Read();
                Environment.Exit(-1);
            }
            if (bufferPassword.Length > passwordBytesLimit)
            {
                Console.WriteLine("【CRITICAL ERROR】密码过长！保存失败！\n【CRITICAL ERROR】操作已回滚，按下任意键退出...");
                Console.Read();
                Environment.Exit(-1);
            }
            //start saving
            //index
            Utility.writeBytesToStream(BitConverter.GetBytes(this.index), ref fs);
            //username
            Utility.writeBytesToStream(FileSystem.systemEncoding.GetBytes(this.username), ref fs);
            tmpBuffer = new byte[usernameBytesLimit - bufferUsername.Length];
            for (int i = 0; i < tmpBuffer.Length; i++) tmpBuffer[i] = (byte)' ';
            Utility.writeBytesToStream(tmpBuffer, ref fs);
            //password
            Utility.writeBytesToStream(FileSystem.systemEncoding.GetBytes(this.password), ref fs);
            tmpBuffer = new byte[passwordBytesLimit - bufferPassword.Length];
            for (int i = 0; i < tmpBuffer.Length; i++) tmpBuffer[i] = (byte)' ';
            Utility.writeBytesToStream(tmpBuffer, ref fs);
            //directoryIndex
            Utility.writeBytesToStream(BitConverter.GetBytes(this.directoryIndex), ref fs);
            fs.Flush();
        }
    }
}
